import { getCookie, createError } from 'h3';

export function getSessionUser(event) {
  const sessionCookie = getCookie(event, 'session');
  if (sessionCookie) {
    try {
      const session = JSON.parse(sessionCookie);
      if (session && session.userId) {
        return {
          userId: session.userId,
          username: session.username,
          name: session.name,
        };
      }
    } catch (error) {
      console.error('Failed to parse session cookie:', error);
    }
  }

  const legacyUserId = getCookie(event, 'userId');
  if (legacyUserId) {
    return { userId: Number(legacyUserId) || legacyUserId };
  }

  return null;
}

export function requireUser(event) {
  const sessionUser = getSessionUser(event);
  if (!sessionUser?.userId) {
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
  }
  return sessionUser;
}
